package com.caption.jdk.stream;

import com.caption.jdk.lambda.Person;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * collections 进行分组操作
 */
public class TestStream06 {

    public static void main(String[] args) {
        /**
         * 按照姓名进行分组
         */
        Map<String, List<Person>> map = Stream.of(new Person("张三", 20),
                new Person("李四", 30),
                new Person("王五", 25),
                new Person("张三", 36)
        ).collect(Collectors.groupingBy(o -> o.getName()));
        map.forEach((k,v)->{
            System.out.println("k="+k+", v="+v);
        });

        /**
         * 先按照姓名进行分组， 在按照年龄大于20进行分组
         */
        System.out.println("---------------------------------------");
        Map<String, Map<String, List<Person>>> map2 = Stream.of(new Person("张三", 20),
                new Person("李四", 30),
                new Person("王五", 25),
                new Person("张三", 36)
        ).collect(Collectors.groupingBy(Person::getName, Collectors.groupingBy(p -> p.getAge() > 20 ? "成年":"未成年" )));
        map2.forEach((k,v)->{
            System.out.println(k);
            v.forEach((k2,v2)->{
                System.out.println("k2="+k2+", v="+v2);
            });
        });

        /**
         * 进行分区操作 把元素分成true和false 两部分
         */
        Map<Boolean, List<Person>> partition = Stream.of(new Person("张三", 20),
                new Person("李四", 30),
                new Person("王五", 25),
                new Person("老刘", 36)
        ).collect(Collectors.partitioningBy(o -> o.getAge() > 25));
        partition.forEach((k,v)->{
            System.out.println("k="+k+", v="+v);
        });

        /**
         * 字符串拼接操作
         */
       String  str = Stream.of(new Person("张三", 20),
                new Person("李四", 30),
                new Person("王五", 25),
                new Person("老刘", 36)).map(Person::getName).collect(Collectors.joining("|","$","&"));
        System.out.println(str);
    }
}
